package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
    @Autowired
    private UserAccountService userAccountService;

    /**
     * 根据充值订单编号查询充值记录
     * @param orderNo
     * @return
     */
    @Override
    public RechargeInfo getRechargeInfo(String orderNo) {
        LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
        return rechargeInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
        //1.构建充值记录对象
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(AuthContextHolder.getUserId());
        //1.1 生成充值订单编号 形式：CZ+日期+雪花算法
        String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdWorker.getIdStr();
        rechargeInfo.setOrderNo(orderNo);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        //2.保存充值记录
        baseMapper.insert(rechargeInfo);
        //3.封装订单编号
        Map<String, String> map = new HashMap<>();
        map.put("orderNo", orderNo);

        //4.TODO 发送延迟消息，延迟关闭充值记录
        return map;
    }

    @Override
    public void rechargePaySuccess(String orderNo) {
        //1.更新充值记录状态，避免先执行延迟关单，再用户付款 采用乐观锁更新  更新失败：发起退款流程
        int count = baseMapper.updateRechargeStatus(orderNo, SystemConstant.ORDER_STATUS_UNPAID, SystemConstant.ORDER_STATUS_PAID);
        if (count == 0) {
            //TODO 更新失败，调用支付服务-发起退款流程
            throw new GuiguException(500, "更新充值（已支付）失败:" + orderNo);
        }
        //2.余额充值
        RechargeInfo rechargeInfo = this.getRechargeInfo(orderNo);
        boolean flag = userAccountService.update(null,
                new LambdaUpdateWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, rechargeInfo.getUserId())
                        .setSql("total_amount = total_amount + " + rechargeInfo.getRechargeAmount())
                        .setSql("available_amount = available_amount + " + rechargeInfo.getRechargeAmount())
                        .setSql("total_income_amount = total_income_amount + " + rechargeInfo.getRechargeAmount())
        );
        if (!flag) {
            throw new GuiguException(500, "充值失败");
        }

            //3.新增账户变动日志
        userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), orderNo);

    }

}